import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { getuserinfo } from '@/api/user'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    children: [

      {
        path: '/',
        name: 'index',
        //  懒加载
        component: () => import(/* webpackChunkName: "login" */ '../views/index.vue')

      },
      // {
      //   path: 'order',
      //   name: 'order',
      //   //  懒加载
      //   component: () => import(/* webpackChunkName: "login" */ '../views/order/index.vue')

      // },
      // {
      //   path: 'order/add',
      //   name: 'orderadd',
      //   //  懒加载
      //   component: () => import(/* webpackChunkName: "login" */ '../views/order/add.vue')

      // },
      // {
      //   path: 'myself',
      //   name: 'myself',
      //   //  懒加载
      //   component: () => import(/* webpackChunkName: "login" */ '../views/order/myself.vue')

      // },
      // {
      //   path: 'order/list',
      //   name: 'list',
      //   //  懒加载
      //   component: () => import(/* webpackChunkName: "login" */ '../views/order/list.vue')

      // },
    ]
  },
  {
    path: '/login',
    name: 'login',
    //  懒加载
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')

  },
  {
    path: '/register',
    name: 'register',
    //  懒加载
    component: () => import(/* webpackChunkName: "login" */ '../views/register.vue')

  },
  {
    path: '/slot',
    name: 'slot',
    //  懒加载
    component: () => import(/* webpackChunkName: "login" */ '../views/slot.vue')

  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '*',
    name: '404',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "notfound" */ '../views/notfound.vue')
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// to 去哪个页面  from   来自哪个页面
// next
let whilelist = ["login", "register"]
router.beforeEach(async (to, from, next) => {


  //  让登录页面 注册页面顺利通过
  if (whilelist.includes(to.name)) {
    next()
    return
  }

  // 判断一下是否有登录的凭证 
  if (localStorage.getItem('token')) {

    //  发现没有菜单 就发生请求 获取菜单更新菜单
    if (store.state.menulist.length == 0) {
      //  这里没有菜单也没路由
      await store.dispatch("getmens") // 加载菜单 加载路由
      // next()
      next(to.path, { replace: true })
    } else {
      next()
    }


  } else {
    next({ name: "login" })  // router.push(  {  }   )
    return
  }






})


export default router
